<!-- 添加优惠券 -->
<template>
  <el-dialog v-model="dialogVisible" title="优惠券增加页" width="80%" :before-close="handleClose">
    <el-form :model="goodForm" ref="formRef" label-width="0">
      <el-table :data="[goodForm]" style="width: 100%">
        <el-table-column label="优惠券金额" width="180">
          <template #default="{ row }">
            <el-form-item prop="amount" class="mb-0">
              <el-input v-model="row.amount" placeholder="请输入优惠券金额"></el-input>
            </el-form-item>
          </template>
        </el-table-column>

        <el-table-column prop="name" label="选择商品" show-overflow-tooltip width="250">
          <template #default="{ row }">
            <el-select v-if="row.isEdit" v-model="row.productId" filterable placeholder="请选择商品" size="small"
              @change="handleProductSelect($event, row)">
              <el-option v-for="item in productOptions" :key="item.productId"
                :label="`${item.productId} - ${item.name}`" :value="item.productId">
                <div class="select-item">
                  <img :src="'http://localhost:8081' + item.image"
                    style="width: 30px; height: 30px; margin-right: 10px;">
                  <span>ID: {{ item.productId }} - {{ item.name }}</span>
                </div>
              </el-option>
            </el-select>
            <span v-else>{{ row.productId }}</span>
          </template>
        </el-table-column>

        <el-table-column label="优惠券数量" width="180">
          <template #default="{ row }">
            <el-form-item prop="quantity" class="mb-0">
              <el-input v-model="row.quantity" placeholder="请输入优惠券数量"></el-input>
            </el-form-item>
          </template>
        </el-table-column>

        <el-table-column label="是否可用" width="180">
          <template #default="{ row }">
            <el-form-item prop="isDelete" class="mb-0">
              <el-select v-model="row.isDelete" placeholder="请选择是否可以使用" class="w-100">
                <el-option label="可以使用" value="0"></el-option>
                <el-option label="不可以使用" value="1"></el-option>
              </el-select>
            </el-form-item>
          </template>
        </el-table-column>
      </el-table>
    </el-form>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleClose">取消</el-button>
        <el-button type="primary" @click="submitForm">确认添加</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<style scoped>
.select-item {
  display: flex;
  align-items: center;
}

.w-100 {
  width: 100%;
}

:deep(.el-table .el-table__cell) {
  padding: 6px 0;
}

:deep(.el-form-item.mb-0) {
  margin-bottom: 0;
}

:deep(.el-input__wrapper) {
  box-shadow: none;
}

:deep(.el-table .cell) {
  padding: 0 10px;
}
</style>

<script setup>
import { ref, reactive, defineEmits, defineExpose, onMounted } from 'vue'
import axios from 'axios'
import { ElMessage } from 'element-plus'

const dialogVisible = ref(false)
const productOptions = ref([])

const goodForm = reactive({
  amount: '',
  productId: '',
  quantity: '',
  isDelete: '0',
  isEdit: true // 添加 isEdit 属性
})

// 获取商品列表
const getProductList = async () => {
  try {
    const response = await axios.get("/getGoods", {
      params: {
        current: 1,
        size: 999
      },
      headers: {
        Authorization: sessionStorage.getItem("Authorization"),
      }
    })

    if (response.data.status === 200) {
      productOptions.value = response.data.data.records
    }
  } catch (error) {
    console.error('获取商品列表失败:', error)
  }
}

// 选择商品处理
const handleProductSelect = (value, row) => {
  row.productId = value
}

const handleClose = () => {
  dialogVisible.value = false
  Object.assign(goodForm, {
    amount: '',
    productId: '',
    quantity: '',
    isDelete: '0',
    isEdit: true
  })
}

const emit = defineEmits(['update:modelValue', 'refresh-list'])

const submitForm = async () => {
  try {
    // 添加表单验证
    if (!goodForm.productId) {
      ElMessage.warning('请选择商品')
      return
    }
    if (!goodForm.amount || goodForm.amount <= 0) {
      ElMessage.warning('请输入有效的优惠券金额')
      return
    }
    if (!goodForm.quantity || goodForm.quantity <= 0) {
      ElMessage.warning('请输入有效的优惠券数量')
      return
    }

    const formData = {
      productId: Number(goodForm.productId),
      amount: Number(goodForm.amount),
      quantity: Number(goodForm.quantity),
      isDelete: goodForm.isDelete
    }

    const response = await axios.post('/addCoupon', formData, {
      headers: {
        Authorization: sessionStorage.getItem("Authorization"),
      },
    })

    if (response.data.status === 200) {
      ElMessage.success('添加优惠券成功')
      handleClose()
      emit('refresh-list')
    } else {
      ElMessage.error(response.data.msg || '添加失败')
    }
  } catch (error) {
    ElMessage.error('添加优惠券失败，请稍后重试')
  }
}

onMounted(() => {
  getProductList()
})

defineExpose({
  dialogVisible
})
</script>